package com.wing.purchase.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.PurEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.purchase.dao.PurReturnGoodsRecordsDao;
import com.wing.purchase.model.entity.*;

import com.wing.purchase.model.request.PurGoodsLogisticsDetailAddForm;
import com.wing.purchase.model.request.PurReturnGoodRecordsUpdateForm;
import com.wing.purchase.model.response.PurReturnGoodRecordsSearchVo;
import com.wing.sell.model.entity.SelGoodsLogistics;
import com.wing.sell.model.entity.SelGoodsLogisticsDetail;
import com.wing.sell.model.entity.SelReturnGoodsRecords;
import com.wing.sell.model.entity.SelReturnGoodsRecordsDetail;
import com.wing.sell.model.request.SelGoodsLogisticsDetailAddForm;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 退货记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurReturnGoodsRecordsServiceImpl extends ServiceImpl<PurReturnGoodsRecordsDao, PurReturnGoodsRecords> implements PurReturnGoodsRecordsService {

    @Autowired
    private PurReturnGoodsRecordsDetailService purReturnGoodsRecordsDetailService;

    //pur_purchase_order
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurGoodsLogisticsService purGoodsLogisticsService;

    @Autowired
    private PurGoodsLogisticsDetailService purGoodsLogisticsDetailService;

    /**
     * 查询退货记录
     * @param pg
     * @param params
     * @return
     */
    @Override
    public Page<PurReturnGoodRecordsSearchVo> pageList4app(Page<PurReturnGoodRecordsSearchVo> pg, Map<String, Object> params) {
        List<PurReturnGoodRecordsSearchVo> list = baseMapper.list4app(pg, params);
        pg.setRecords(list);
        return pg;
    }

    /**
     * 添加退货记录
     * @param form
     * @return
     */
    @Override
    @Transactional
    public int addReturnRecordsGoods(PurReturnGoodRecordsUpdateForm form) {
        //1. 添加记录
        PurReturnGoodsRecords records = new PurReturnGoodsRecords();
        BeanUtil.copyProperties(form,records,true);
        records.setStatus(PurEnum.returnGoodStatus.DSH.getCode());
        String code = UniqueIdGeneratorUtil.generateUniqueId("TH", "yyyyMMdd", 1000, 9999);
        records.setCode(code);
        records.setCreateTime(LocalDateTime.now());
        records.setCreatorName(JwtUtils.getLoginUsername());
        records.setCreator(JwtUtils.getLoginUserId());
        boolean save = this.save(records);
        if (save){
            //2. 添加明细
            List<PurReturnGoodsRecordsDetail> purReturnRecordDetails = form.getPurReturnRecordDetails();
            if (CollectionUtils.isNotEmpty(purReturnRecordDetails)){
                purReturnRecordDetails.forEach(info->{
                    info.setRecordId(records.getId());
                    info.setCreateTime(LocalDateTime.now());
                    info.setCreatorName(JwtUtils.getLoginUsername());
                    info.setCreator(JwtUtils.getLoginUserId());
                });
                boolean saveBatch = purReturnGoodsRecordsDetailService.saveBatch(purReturnRecordDetails);
                if (saveBatch){
                    return 1;
                }
            }else{
                return 1;
            }
        }
        return 0;
    }

    /**
     * 修改退货记录
     * @param form
     * @return
     */
    @Override
    @Transactional
    public int updateReturnRecordsGoods(PurReturnGoodRecordsUpdateForm form) {
        //1.修改记录
        PurReturnGoodsRecords byId = this.getById(form.getId());
        BeanUtil.copyProperties(form,byId,true);
        byId.setStatus(PurEnum.returnGoodStatus.DSH.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean b = this.updateById(byId);
        if (b){
            //2.修改详情
            QueryWrapper<PurReturnGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("record_id",byId.getId());
            boolean remove = purReturnGoodsRecordsDetailService.remove(queryWrapper);
            if (remove) {
                List<PurReturnGoodsRecordsDetail> purReturnRecordDetails = form.getPurReturnRecordDetails();
                if (CollectionUtils.isNotEmpty(purReturnRecordDetails)) {
                    purReturnRecordDetails.forEach(info -> {
                        info.setRecordId(byId.getId());
                        info.setCreateTime(LocalDateTime.now());
                        info.setCreatorName(JwtUtils.getLoginUsername());
                        info.setCreator(JwtUtils.getLoginUserId());
                    });
                    boolean saveBatch = purReturnGoodsRecordsDetailService.saveBatch(purReturnRecordDetails);
                    if (saveBatch) {
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 查询退货记录详情
     * @param recordId
     * @return
     */
    @Override
    public PurReturnGoodRecordsUpdateForm getByDetailId(String recordId) {
        PurReturnGoodRecordsUpdateForm form = new PurReturnGoodRecordsUpdateForm();
        //1.查询记录信息 
        PurReturnGoodsRecords byId = this.getById(recordId);
        BeanUtil.copyProperties(byId,form,true);
        PurchaseOrder purchaseOrder = purchaseOrderService.getById(byId.getPurOrderId());
        if (ObjectUtil.isNotEmpty(purchaseOrder)){
            form.setPurOrderCode(purchaseOrder.getSn());
        }
        //2. 查询明细信息
        QueryWrapper<PurReturnGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_id",recordId);
        List<PurReturnGoodsRecordsDetail> list = this.purReturnGoodsRecordsDetailService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)){
            //查询 退货收货信息
            QueryWrapper<PurGoodsLogistics> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("record_id", byId.getId());
            detailQueryWrapper.eq("module_type", PurEnum.moduleTypeBylogistics.XSTH.getCode());
            detailQueryWrapper.eq("good_type", PurEnum.goodSellType.HH.getCode());
            detailQueryWrapper.eq("is_deleted", false);
            List<PurGoodsLogistics> infos = this.purGoodsLogisticsService.list(detailQueryWrapper);
            //查询 退换详情
            for (PurGoodsLogistics selGoodsLogistics : infos) {
                List<PurGoodsLogisticsDetail> listBy = this.purGoodsLogisticsDetailService.getListBy(selGoodsLogistics.getId());
                selGoodsLogistics.setSelGoodsLogisticsDetails(listBy);
            }
            form.setSendSelGoodsLogisticsDetails(infos);
           form.setPurReturnRecordDetails(list);
        }
        return form;
    }

    /**
     * 删除退货记录
     * @param recordId
     * @return
     */
    @Override
    @Transactional
    public boolean deleteBy(String recordId) {
        boolean b = this.removeById(recordId);
        if (b){
            QueryWrapper<PurReturnGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("record_id",recordId);
            boolean remove = this.purReturnGoodsRecordsDetailService.remove(detailQueryWrapper);
            if (remove){
                return true;
            }
        }
        return false;
    }


    /**
     * 采购退货发货物流信息补全
     * @param purGoodsLogisticsDetailAddForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addLogisticsInfo(PurGoodsLogisticsDetailAddForm purGoodsLogisticsDetailAddForm) {
        //添加发货记录
        PurGoodsLogistics purGoodsLogistics = new PurGoodsLogistics();
        BeanUtil.copyProperties(purGoodsLogisticsDetailAddForm, purGoodsLogistics, false);
        purGoodsLogistics.setCreateTime(LocalDateTime.now());
        purGoodsLogistics.setModifier(JwtUtils.getLoginUserId());
        purGoodsLogistics.setCreator(JwtUtils.getLoginUserId());
        //code
        String code = UniqueIdGeneratorUtil.generateUniqueId("WLTH", "yyyyMMdd", 1000, 9999);
        purGoodsLogistics.setCode(code);
        purGoodsLogistics.setCreatorName(JwtUtils.getLoginUsername());
        boolean save = purGoodsLogisticsService.save(purGoodsLogistics);
        if (save) {
            //拿到详情
            List<PurGoodsLogisticsDetail> formDetails = purGoodsLogisticsDetailAddForm.getDetails();
            for (PurGoodsLogisticsDetail formDetail : formDetails) {
                formDetail.setLogisticsId(purGoodsLogistics.getId());
                formDetail.setCreateTime(LocalDateTime.now());
                formDetail.setModifier(JwtUtils.getLoginUserId());
                formDetail.setCreatorName(JwtUtils.getLoginUsername());
                formDetail.setCreator(JwtUtils.getLoginUserId());
            }
            //插入发货详情
            boolean saved = purGoodsLogisticsDetailService.saveBatch(formDetails);
            if (saved) {
                //1. 修改record的信息
                Long recordId = purGoodsLogisticsDetailAddForm.getRecordId();
                PurReturnGoodsRecords byId = this.getById(recordId);
                //收货
                if (purGoodsLogisticsDetailAddForm.getGoodType().equals(PurEnum.goodSellType.TH.getCode())){
                    //查询当前是否全部签收完毕
                    QueryWrapper<PurReturnGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("record_id", recordId);
                    List<PurReturnGoodsRecordsDetail> list = this.purReturnGoodsRecordsDetailService.list(detailQueryWrapper);
                    AtomicReference<Boolean> isOk = new AtomicReference<>(true);
                    if (CollectionUtils.isNotEmpty(list)) {
                        list.forEach(info->{
                            //获取
                            BigDecimal result = this.baseMapper.getSendQuantityForLogistics(info.getId(),PurEnum.moduleTypeBylogistics.XSTH.getCode());
                            if (result.compareTo(info.getMainQuantity())<0){
                                isOk.set(false);
                            }
                        });
                    }
                    if (isOk.get()) {
                        byId.setStatus(PurEnum.purReturnGoodStatus.YFH.getCode());
                    }
                }
                //设置状态为已收货
                byId.setCreateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                boolean b = this.updateById(byId);
                if (b){
                    return 1;
                }
            }


        }
        return 0;
    }
}
